package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.dao.impl.UserDaoImpl;
import com.rdc.example.entity.User;
import com.rdc.example.service.UserService;
import com.rdc.example.util.HashUtil;

import java.util.*;

/**
 * @author Wookie
 * @description 用户service业务层接口实现类
 */
public class UserServiceImpl implements UserService {



    private final UserDaoImpl userDao = new UserDaoImpl();
    public UserDTO userDTO = new UserDTO();
    public User userEntity=new User();

    public static void main(String[] args) throws Exception {
        UserServiceImpl userService = new UserServiceImpl();
        System.out.println(userService.getUserByUserName("管理员"));

    }

    /**
     * 用户注登录
     * @param userName 用户名称
     * @param password 用户明文密码
     * @return 是否登录成功
     */
    @Override
    public Result login(String userName, String password) throws Exception {
        try {
            boolean login = userDao.login(userName, password);
            return login ? Result.success("登录成功", null)
                    : Result.fail("登录失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户注册
     * @param userDTO 用户对象（包含明文密码）
     * @return 是否注册成功
     */
    @Override
    public Result register(UserDTO userDTO) throws Exception {
        if (userDTO.getPassword().length() < 6 || userDTO.getPassword().length() > 15) {
            System.out.println("密码长度需为6-15位！");
            return Result.fail("登录失败", null);
        }
        try{
        User userEntity  = convertToEntity(userDTO);
        boolean register = userDao.insert(userEntity);
        return register  ? Result.success("注册成功", null)
                    : Result.fail("注册失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户信息展示
     * @param userName 用户名称
     * @return userDTO
     */
    @Override
    public UserDTO getUserByUserName(String userName) throws Exception{
        try{
            userEntity = userDao.getUserByName(userName);
            userDTO = convertToDto(userEntity);
            return userDTO;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param keyword
     * @return
     * @throws Exception
     */
    @Override
    public List<UserDTO> searchUsersByName(String keyword) throws Exception {
        try {
            List<UserDTO> userDTOList = new ArrayList<>();
            List<User> userList = userDao.searchUsersByName(keyword);
            if (userList == null || userList.isEmpty()) {
                return userDTOList;
            }
            return convertToDtoList(userList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param userIds
     * @return
     */
    @Override
    public List<UserDTO> getUserDTOListByIds(List<Integer> userIds) {
        try {
            List<UserDTO> userDTOList = new ArrayList<>();
//            List<User> result = new ArrayList<>();
            UserDTO userDTO = new UserDTO();
            Set<Integer> uniqueIds = new HashSet<>(userIds);
            Map<Integer, User> userMap = userDao.getUsersByIds(uniqueIds);
            for (Integer id : userIds) {
                User user = userMap.get(id);
                userDTO.setUserName(user.getUserName());
                userDTO.setId(user.getId());
                userDTOList.add(userDTO);
            }
            return userDTOList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    // 将entity.User转换为bean.User
    private UserDTO convertToDto(User entity) {
        UserDTO dto = new UserDTO();
        dto.setId(entity.getId());
        dto.setUserName(entity.getUserName());
        dto.setEmail(entity.getEmail());
        dto.setCreatedAt(entity.getCreatedAt().toString());
        dto.setPower(entity.getPower() != 0);
        dto.setStatus(entity.getStatus() !=0);
        return dto;
    }
    // 将bean.User转换为entity.User
    private User convertToEntity(UserDTO dto) {
        User entity = new User();
        entity.setUserName(dto.getUserName());
        String hashedPassword = HashUtil.getSaltMD5(dto.getPassword());
        entity.setPasswordHash(hashedPassword);
        entity.setEmail(dto.getEmail());
        Integer power=dto.getPower()?1:0;
        entity.setPower(power);
        Integer status=dto.getStatus()?1:0;
        entity.setStatus(status);
        return entity;
    }
    private List<UserDTO> convertToDtoList(List<User> entityList) {
        List<UserDTO> dtos = new ArrayList<>();
        for (User entity : entityList) {
            dtos.add(convertToDto(entity));
        }
        return dtos;
    }

    private List<User> convertToEntityList(List<UserDTO> dtoList) {
        List<User> entityList = new ArrayList<>();
        for (UserDTO dto : dtoList) {
            entityList.add(convertToEntity(dto));
        }
        return entityList;
    }
}
